import { Col, Row, message as MessageBox } from 'antd'
import { useState, useContext, useEffect, useRef } from 'react'
import SendArea from '@/components/SendArea'
import ChatItem from './components/ChatItem'
import { AppContext } from '@/store'
import { SendQuestionAPI } from '@/apis'
import { toString } from '../../utils'
import { useNavigate, useLocation } from 'react-router-dom'
import stopIcon from '@/assets/stop_icon.png'
import './index.less'

let controller=null
const Chat = () => {
  const { state, dispatch } = useContext(AppContext)
  const sendRef = useRef()
  const navigate = useNavigate()
  const location = useLocation()

  const sendQuestion = (keyword) => {
    dispatch({ type: 'SET_IS_STOP', payload: false })
    controller = new AbortController()
    const signal = controller.signal
    // 发送ai提问
    SendQuestionAPI(
      {
        q: keyword, // state.messageList[0].content, //提问的问题
        stream: 1, //1为sse，0为普通数据响应
        modelname: 'qwen-max', //模型名称， 可以让用户配置
      },
      navigate,
      signal,
    )
      .then(async (response) => {
        dispatch({ type: 'SET_IS_REPLY', payload: true })
        const reader = response.body.getReader()
        const messages = state.messageList
        let message = {
          type: 'system',
          content: '',
        }
        messages.push(message)
        dispatch({ type: 'SET_MESSAGE_LIST', payload: messages })
        while (true) {
          const { done, value } = await reader.read();

          if (done) {
            console.log('回复完了')
            dispatch({ type: 'SET_IS_REPLY', payload: false })

            break
          }
          const valueStr = toString(value)
          const message = state.messageList[state.messageList.length - 1]
          message.content += valueStr

          dispatch({ type: 'UPDATE_LAST_MESSAGE', payload: message })
        }
      })
      .catch(() => {
        dispatch({ type: 'SET_IS_REPLY', payload: false })
      })
  }
  const sendHandle = (keyword) => {
    if (state.isReply) {
      MessageBox.warning('回复完成后才可发送')
      return
    }
    // 添加提问
    let message = {
      type: 'user',
      content: keyword,
    }
    const messageList = state.messageList
    messageList.push(message)
    dispatch({ type: 'SET_MESSAGE_LIST', payload: messageList })
    sendQuestion(keyword)
    sendRef.current.resetContent()
  }
 

  const stopHandle = () => {
    dispatch({ type: 'SET_IS_REPLY', payload: false })
    dispatch({ type: 'SET_IS_STOP', payload: true })
    controller.abort()
  }

  useEffect(() => {
    if (!state.token) {
      navigate('/')
      return
    }
    const currentPath = location.pathname
    dispatch({ type: 'SET_PATHNAME', payload: currentPath })

    if (state.messageList.length === 1) {
      sendQuestion(state.messageList[0].content)
    }
  }, [])
  useEffect(() => {
    const chatBox = document.querySelector('.chat-message')
    chatBox.scrollTop = chatBox.scrollHeight
  })
  return (
    <Row className="chat-content">
      <Col className="content">
        <Col className="chat-message">
          <Col className="chat-list">
            {state.messageList.map((item, index) => (
              <ChatItem item={item} key={index} />
            ))}
          </Col>
        </Col>
        <Col className="chat-content-bootom">
          {
            !state.isStop && state.isReply ?  <Col className="stop-btn btn" onClick={stopHandle}>
            <img src={stopIcon} alt="" />
            <span>停止回答</span>
          </Col>: null
          }
         
          <SendArea sendHandle={sendHandle} ref={sendRef} />
        </Col>
      </Col>
    </Row>
  )
}

export default Chat
